<template>
  <div>
    <div class="mb-3">
      <el-button
        v-if="customerData.project_status === '0' || customerData.project_status === '2'"
        type="primary"
        @click="dialogVisible = true"
      >
        增加设备设施
      </el-button>
    </div>
    <loading-wrap>
      <el-table border :data="tableData">
        <el-table-column align="center" label="类型">
          <template slot-scope="scope">
            {{ enumProduceType[scope.row.business_fac_type] || '-' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="名称" prop="fac_name">
          <template slot-scope="scope">
            {{ scope.row.fac_name || '-' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="状态">
          <template slot-scope="scope">
            {{ enumFacilityStatusType[scope.row.sit_type] || '-' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="规模" prop="scale">
          <template slot-scope="scope">
            {{ scope.row.scale || '-' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="单位" prop="uscale">
          <template slot-scope="scope">
            {{ scope.row.uscale || '-' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="备注" prop="remark">
          <template slot-scope="scope">
            {{ scope.row.remark || '-' }}
          </template>
        </el-table-column>
        <el-table-column
          v-if="customerData.project_status === '0' || customerData.project_status === '2'"
          align="center"
          label="操作"
          width="100px"
        >
          <template v-if="scope.row.submit_type !== '1'" slot-scope="scope">
            <el-button class="py-0 px-1" type="text" @click="edit(scope.row)">
              <i class="fa fa-edit"></i>
            </el-button>
            <el-button class="py-0 px-1 text-danger" type="text" @click="deleteData(scope.row)">
              <i class="fa fa-trash"></i>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </loading-wrap>

    <el-dialog
      title="新增设备设施"
      width="70%"
      :close-on-click-modal="false"
      :before-close="handleClose"
      :visible.sync="dialogVisible"
    >
      <el-table border v-loading="industloading" :data="postData">
        <el-table-column align="center" label="类型">
          <template slot-scope="scope">
            <el-select v-model="scope.row.business_fac_type">
              <el-option
                v-for="(label, key) in enumProduceType"
                :key="key"
                :label="label"
                :value="key"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" label="名称" width="120px">
          <template slot-scope="scope">
            <select-busname
              v-if="scope.row.business_fac_type === '2'"
              v-model="scope.row.fac_name"
            ></select-busname>
            <select-facname v-else v-model="scope.row.fac_name"></select-facname>
          </template>
        </el-table-column>
        <el-table-column align="center" label="状态" width="120px">
          <template slot-scope="scope">
            <el-select v-model="scope.row.sit_type">
              <el-option
                v-for="(label, key) in enumFacilityStatusType"
                :key="key"
                :label="label"
                :value="key"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" label="规模">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.scale"
              style="width: 100%"
              :controls="false"
              :min="0"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column align="center" label="规模单位" width="90px">
          <template slot-scope="scope">
            <el-input v-model="scope.row.uscale"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="备注">
          <template slot-scope="scope">
            <el-input v-model="scope.row.remark"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="60px">
          <template slot-scope="scope">
            <el-button class="py-0 px-1 text-danger" type="text" @click="deleteArray(scope.$index)">
              <i class="fa fa-trash"></i>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="mt-3">
        <el-row :gutter="20">
          <el-col :span="3">
            <el-button @click="postData.push({})">新增一行</el-button>
          </el-col>
          <el-col :span="2">
            <el-button style="width: 100%" @click="clearClose">取消</el-button>
          </el-col>
          <el-col :span="2">
            <el-button style="width: 100%" :loading="industloading" @click="submit">
              <span>保存</span>
            </el-button>
          </el-col>
        </el-row>
      </div>
    </el-dialog>

    <form-component
      ref="fc"
      :auto-init="false"
      :form-data="formData"
      :table-data="editData"
      :table-id="tableId"
      :table-name="tableName"
      :visible.sync="editVisible"
      @success="getData"
    ></form-component>
  </div>
</template>
<script>
import FormComponent from '@/components/FormComponent'
import SelectFacname from '@/credit/components/select/SelectFacname'
import SelectBusname from '@/credit/components/select/SelectBusinesName'
import { enumFacilityStatusType, enumFacilityType, enumProduceType } from '@/credit/plugins/enum'

export default {
  components: {
    SelectBusname,
    SelectFacname,
    FormComponent,
  },
  props: {},
  data() {
    return {
      enumProduceType,
      enumFacilityStatusType,
      enumFacilityType,
      tableData: [],
      editVisible: false,
      tableName: 'datum_customer_business_facilities',
      formData: {
        business_fac_type: {
          type: 'radio',
          label: '类型',
          value: '1',
          inline: true,
          enumType: enumProduceType,
          required: true,
          onClick: v => {
            const type = +v === 1
            const ref = this.$refs.fc
            type
              ? ref.setKey('fac_name', 'component', SelectFacname)
              : ref.setKey('fac_name', 'component', SelectBusname)
          },
        },
        fac_name: {
          type: 'component',
          label: '名称',
          value: '',
          component: SelectFacname,
          required: true,
          attrs: { css: 'form-control-ml' },
        },
        fac_type: {
          type: 'radio',
          value: '1',
          label: 'type',
          required: true,
          enumType: enumFacilityType,
          inline: true,
          hide: true,
          redundancy: fd => this.$utils.findKeyFromValue(enumFacilityType, fd.fac_name.value, 12),
        },
        scale: { type: 'number', label: '规模', value: '', required: true, step: 1 },
        sit_type: {
          type: 'radio',
          label: '状态',
          value: '1',
          inline: true,
          enumType: enumFacilityStatusType,
          required: true,
        },
        uscale: { type: 'text', label: '单位', value: '' },
        remark: { type: 'text', label: '备注', value: '' },
      },
      tableId: '',
      editData: {},
      dialogVisible: false,
      industloading: false,
      postData: [{}, {}, {}],
    }
  },
  computed: {},
  watch: {},
  created() {
    this.customerData = JSON.parse(sessionStorage.getItem('customer_related_view'))
    this.id = this.$route.query.id || sessionStorage.getItem('customer_related_id')
    this.getData()
  },
  mounted() {},
  methods: {
    deleteArray(index) {
      this.postData.splice(index, 1)
    },
    submit() {
      let customerData = {}
      let data = []
      for (let p of this.postData) {
        if (JSON.stringify(p) !== '{}') {
          const localCustomerData = sessionStorage.getItem('customer_related_view')
          try {
            customerData = JSON.parse(localCustomerData)
          } catch (e) {
            console.error(e)
          }
          p.customer_id = customerData.customer_id
          p.customer_name = customerData.customer_name
          p.customer_related_id = this.id
          data.push(p)
        }
      }
      if (data.length > 0) {
        this.toSave(data)
      } else {
        this.$message.warning('请输入信息！')
      }
    },
    async toSave(data) {
      this.industloading = true
      const [res, err] = await this.$utils.promise(
        this.$api.addBatch('credit', this.tableName, data)
      )
      this.industloading = false
      if (res) {
        this.$message.success('数据采集成功！')
        this.getData()
        this.clearClose()
      } else {
        this.$message.error(`数据采集失败，请重试！（${err.status}）`)
      }
    },
    handleClose() {
      this.dialogVisible = false
    },
    clearClose() {
      this.dialogVisible = false
      this.postData = [{}, {}, {}]
    },
    getData() {
      this.$api
        .getData('credit', this.tableName, {
          'customer_related_id.eq': this.id,
        })
        .then(res => {
          this.tableData = res.data
        })
    },
    edit(p) {
      this.editVisible = true
      this.tableId = p ? p.id : ''
      this.editData = p
    },
    deleteData(item) {
      const h = this.$createElement
      this.$msgbox({
        title: '提示',
        message: h('span', undefined, `确定删除？`),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '删除中...'
            const [res] = await this.$utils.promise(
              this.$api.deleteData('credit', this.tableName, item.id)
            )
            instance.confirmButtonLoading = false
            instance.confirmButtonText = '确定'
            if (res) {
              this.$message.success('删除成功！')
              this.getData()
              done()
            } else {
              this.$message.error('删除失败，请重试！')
            }
          } else {
            done()
          }
        },
      }).catch(() => {})
    },
  },
}
</script>
<style scoped></style>
